﻿using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace AuthExtensions.Auth
{
    public class AuthToken : IAuthToken
    {



        private IHttpContextAccessor _accessor;
        private AuthConfig _authConfig;
        public AuthToken(IHttpContextAccessor accessor, IOptionsMonitor<AuthConfig> authConfig)
        {
            _accessor = accessor;
            _authConfig = authConfig.CurrentValue;
        }

        public TokenDto Build(Claim[] claims)
        {

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_authConfig.SigningKey));
            var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var now = DateTime.Now;
            var token = new JwtSecurityToken(
                issuer: _authConfig.ValidIssuer,
                audience: _authConfig.ValidAudience,
                claims: claims,
                notBefore: now,
                expires: now.AddMinutes(_authConfig.ExpirationMinutes),
                signingCredentials: signingCredentials
            );
            return new TokenDto { Token = new JwtSecurityTokenHandler().WriteToken(token), ExpiresIn = now.AddMinutes(_authConfig.ExpirationMinutes), Now = now };
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="claims"></param>
        /// <returns></returns>
        public Task BuildIdentity(Claim[] claims)
        {
            var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
            identity.AddClaims(claims);
            if (_accessor.HttpContext == null) return Task.CompletedTask;
            return _accessor.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                 new ClaimsPrincipal(identity),
                 new AuthenticationProperties
                 {
                     ExpiresUtc = DateTime.Now.AddMinutes(_authConfig.ExpirationMinutes),
                     IsPersistent = true
                 });

        }
    }
}
